﻿// <copyright file="ShellViewModel.cs" company="EffuEfface">
//      Copyright (c) Effu Efface Consulting  All rights reserved.
// </copyright>
// <author>Ryan R. Sites</author>

namespace TVersiPlay
{
    using System.Configuration;
    using System.Windows.Input;
    using Microsoft.Practices.Prism.Commands;
    using Microsoft.Practices.Prism.Events;
    using Microsoft.Practices.Unity;
    using TVersiPlay.Common;
    using TVersiPlay.Common.Interfaces;
    using TVersiPlay;
    using TVersiPlay.Events;
    using System.Xml;
    using System;
    using System.ComponentModel;
    using System.Threading;
    using System.Windows.Threading;

    public class ShellViewModel: INotifyPropertyChanged
    {
        #region declarations
        
        private INavigationService navigate;
        private IUnityContainer container;
        private IAppSettingsService appSettings;
        private IEventAggregator eventAggregator;
        private IUPnPControlPointService upnpService;

        public ICommand NavigateHome { get; private set; }
        public ICommand TestNavigate { get; private set; }


        string statusText = "kiss my grits";
        bool isBusy;

        #endregion //declarations

        #region constructors

        public ShellViewModel(IUnityContainer container)
         {
            this.container = container;
            this.navigate = this.container.Resolve<INavigationService>();
            this.appSettings = this.container.Resolve<IAppSettingsService>();
            this.eventAggregator = this.container.Resolve<IEventAggregator>();
            this.upnpService = this.container.Resolve<IUPnPControlPointService>();

            this.eventAggregator.GetEvent<SettingsUpdatedEvent>().Subscribe(this.OnSettingsUpdated, ThreadOption.PublisherThread);
            this.eventAggregator.GetEvent<LongRunningProcessEvent>().Subscribe(this.LongRunningProcessUpdated,ThreadOption.UIThread);

            this.NavigateHome = new DelegateCommand<object>(this.OnNavigateToHome, this.CanNavigateToHome);
            this.TestNavigate = new DelegateCommand<object>(this.OnTestNavigate);
            this.SetAppSettings();
           
            this.upnpService.Start();
         }

        #endregion //constructors

        #region properties

        public string StatusText 
        {  
            get { return this.statusText;}
            set
            {
                this.statusText = value;
                this.OnPropertyChanged("StatusText");
            }
        }

        public bool IsBusy
        {
            get { return this.isBusy ; }
            set
            {
                this.isBusy = value;
                this.OnPropertyChanged("IsBusy");
            }
        }

        #endregion //properties

        #region methods

        private void OnNavigateToHome(object paramater)
        {
            this.navigate.NavigateViewToRegion(ViewNames.MainMenuView, RegionNames.MainRegion);
        }

        private void OnTestNavigate(object paramater)
        {
            this.navigate.NavigateViewToRegion(ViewNames.ThreeOrMoreMusicView, RegionNames.BrowseResultsRegion);
        }

        private bool CanNavigateToHome(object paramater)
        {
            return true;
        }

        private void SetAppSettings()
        {
            DTO.AppSettings settingsToInitialize = new DTO.AppSettings();

            settingsToInitialize.UPnPServerId = Properties.Settings.Default.UPnPServerId;            

            this.appSettings.InitializeSettings(settingsToInitialize);
        }

        private void OnSettingsUpdated(DTO.AppSettings settingsToSave)
        {
            if (settingsToSave != null)
            {
                Properties.Settings.Default.UPnPServerId = settingsToSave.UPnPServerId;
                Properties.Settings.Default.Save();
            }
        }

        private void LongRunningProcessUpdated(DTO.LongRunningProcess results)
        {         

            Action<bool,string> updateStatus = (isBusy,busyMessage) => 
            {
                if (isBusy)
                {
                    this.StatusText = busyMessage;
                    if (results.ShowPopUp)
                        this.IsBusy = true;
                }

                else
                {
                    this.StatusText = string.Empty;
                    this.IsBusy = false;
                }
                   
            };

            Dispatcher.CurrentDispatcher.BeginInvoke(updateStatus, DispatcherPriority.Background,results.IsBusy,results.BusyMessage);                    
        }             

        private void UpdateConfig(string key, string value)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

            foreach (XmlElement element in xmlDoc.DocumentElement)
            {
                if (element.Name.Equals("appSettings"))
                {
                    foreach (XmlNode node in element.ChildNodes)
                    {
                        if (node.Attributes[0].Value.Equals(key))
                        {
                            node.Attributes[1].Value = value;
                        }
                    }
                }
            }

            xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);            

        }
        #endregion //methods

        #region events
        #endregion //events

        #region INotifyPropertyChanged Items

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null)
                Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }
}
